{% extends "base.html" %}

{% block title %}用户管理 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1.5rem;
    }
    
    .search-box {
        padding: 0.5rem 1rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        width: 300px;
    }
    
    .users-table {
        width: 100%;
        border-collapse: collapse;
    }
    
    .users-table th,
    .users-table td {
        padding: 0.75rem;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .users-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #2c3e50;
    }
    
    .users-table tr:hover {
        background: #f8f9fa;
    }
    
    .badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .badge-admin {
        background: #e74c3c;
        color: white;
    }
    
    .badge-teacher {
        background: #3498db;
        color: white;
    }
    
    .badge-student {
        background: #2ecc71;
        color: white;
    }
    
    .badge-active {
        background: #d4edda;
        color: #155724;
    }
    
    .badge-inactive {
        background: #f8d7da;
        color: #721c24;
    }
    
    .action-btn {
        padding: 0.25rem 0.75rem;
        margin: 0 0.25rem;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.85rem;
    }
    
    .btn-edit {
        background: #3498db;
        color: white;
    }
    
    .btn-delete {
        background: #e74c3c;
        color: white;
    }
    
    .modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0,0,0,0.5);
        z-index: 1000;
    }
    
    .modal-content {
        background: white;
        max-width: 600px;
        margin: 5% auto;
        padding: 2rem;
        border-radius: 8px;
        max-height: 80vh;
        overflow-y: auto;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 500;
    }
    
    .form-group input,
    .form-group select,
    .form-group textarea {
        width: 100%;
        padding: 0.5rem;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
    }
    
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0.5rem;
        margin-top: 1.5rem;
    }
    
    .pagination button {
        padding: 0.5rem 1rem;
        border: 1px solid #e0e0e0;
        background: white;
        cursor: pointer;
        border-radius: 4px;
    }
    
    .pagination button:hover:not(:disabled) {
        background: #3498db;
        color: white;
    }
    
    .pagination button:disabled {
        opacity: 0.5;
        cursor: not-allowed;
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom:1.5rem;">用户管理</h2>

<div class="card">
    <div class="toolbar">
        <input type="text" id="search-input" class="search-box" placeholder="搜索学号、工号、姓名、学院、系部...">
        <button class="btn btn-primary" onclick="showCreateModal()">+ 创建用户</button>
    </div>
    
    <div id="loading" class="loading" style="display:none;">
        <div class="spinner"></div>
        <p>加载中...</p>
    </div>
    
    <table class="users-table" id="users-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>学号/工号</th>
                <th>姓名</th>
                <th>学院</th>
                <th>系部</th>
                <th>邮箱</th>
                <th>专业/职称</th>
                <th>年级</th>
                <th>入学日期</th>
                <th>角色</th>
                <th>状态</th>
                <th>创建时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="users-tbody">
        </tbody>
    </table>
    
    <div class="pagination" id="pagination"></div>
</div>

<!-- 创建/编辑用户模态框 -->
<div id="user-modal" class="modal">
    <div class="modal-content">
        <h3 id="modal-title">创建用户</h3>
        <form id="user-form" onsubmit="return false;">
            <input type="hidden" id="user-id">
            
            <div class="form-group">
                <label>用户名 *</label>
                <input type="text" id="username" required>
            </div>
            
            <div class="form-group">
                <label>邮箱</label>
                <input type="email" id="email" placeholder="可选">
            </div>
            
            <div class="form-group">
                <label>密码 <span id="password-hint">(留空则不修改)</span></label>
                <input type="password" id="password">
            </div>
            
            <div class="form-group">
                <label>角色 *</label>
                <select id="role" required onchange="handleRoleChange()">
                    <option value="student">学生</option>
                    <option value="teacher">教师</option>
                    <option value="admin">管理员</option>
                </select>
            </div>
            
            <div class="form-group">
                <label>姓 *</label>
                <input type="text" id="first-name" required>
            </div>
            
            <div class="form-group">
                <label>名 *</label>
                <input type="text" id="last-name" required>
            </div>
            
            <div class="form-group">
                <label>所属学院 *</label>
                <input type="text" id="college" required>
            </div>
            
            <div class="form-group">
                <label>所属系部 *</label>
                <input type="text" id="department" required>
            </div>
            
            <div class="form-group">
                <label>手机号</label>
                <input type="text" id="phone">
            </div>
            
            <!-- 学生专属字段 -->
            <div id="student-fields" style="display:none;">
                <div class="form-group">
                    <label>学号</label>
                    <input type="text" id="student-id">
                </div>
                <div class="form-group">
                    <label>专业</label>
                    <input type="text" id="major">
                </div>
                <div class="form-group">
                    <label>年级</label>
                    <select id="grade-level">
                        <option value="1">大一</option>
                        <option value="2">大二</option>
                        <option value="3">大三</option>
                        <option value="4">大四</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>入学日期</label>
                    <input type="date" id="enrollment-date">
                </div>
            </div>
            
            <!-- 教师专属字段 -->
            <div id="teacher-fields" style="display:none;">
                <div class="form-group">
                    <label>工号</label>
                    <input type="text" id="employee-id">
                </div>
                <div class="form-group">
                    <label>院系</label>
                    <input type="text" id="teacher-department">
                </div>
                <div class="form-group">
                    <label>职称</label>
                    <input type="text" id="title">
                </div>
            </div>
            
            <div style="display:flex;gap:1rem;margin-top:1.5rem;">
                <button type="button" class="btn btn-primary" onclick="saveUser()" style="flex:1;">保存</button>
                <button type="button" class="btn btn-danger" onclick="closeModal()" style="flex:1;">取消</button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    let currentPage = 1;
    let totalPages = 1;
    let allUsers = [];
    
    async function loadUsers() {
        try {
            document.getElementById('loading').style.display = 'block';
            
            // 加载所有学生和教师（增加per_page以确保加载所有用户）
            const data = await apiRequest(`/students?page=1&per_page=2000`);
            const teachers = await apiRequest(`/teachers?page=1&per_page=200`);
            
            // 合并所有用户
            allUsers = [...data.data, ...teachers.data];
            
            renderUsers(allUsers);
            
            document.getElementById('loading').style.display = 'none';
        } catch (error) {
            showAlert('加载用户失败: ' + error.message, 'error');
            document.getElementById('loading').style.display = 'none';
        }
    }
    
    function renderUsers(users) {
        const tbody = document.getElementById('users-tbody');
        
        if (users.length === 0) {
            tbody.innerHTML = '<tr><td colspan="10" style="text-align:center;">暂无数据</td></tr>';
            return;
        }
        
        tbody.innerHTML = users.map(user => {
            // 根据角色显示学号或工号
            let idNumber = user.username; // 默认使用username（现在已经是学号/工号了）
            if (user.role === 'student' && user.profile && user.profile.student_id) {
                idNumber = user.profile.student_id;
            } else if (user.role === 'teacher' && user.profile && user.profile.employee_id) {
                idNumber = user.profile.employee_id;
            }
            
            return `
                <tr>
                    <td>${user.id}</td>
                    <td>${idNumber}</td>
                    <td>${user.last_name || ''}${user.first_name || ''}</td>
                    <td>${user.college || '-'}</td>
                    <td>${user.department || '-'}</td>
                    <td>${user.email || '-'}</td>
                    <td>${user.role === 'student' ? (user.profile?.major || '-') : (user.profile?.title || '-')}</td>
                    <td>${user.role === 'student' ? (user.profile?.grade_level ?? '-') : '-'}</td>
                    <td>${user.role === 'student' && user.profile?.enrollment_date ? new Date(user.profile.enrollment_date).toLocaleDateString() : '-'}</td>
                    <td><span class="badge badge-${user.role}">${getRoleName(user.role)}</span></td>
                    <td><span class="badge badge-${user.is_active ? 'active' : 'inactive'}">${user.is_active ? '激活' : '禁用'}</span></td>
                    <td>${new Date(user.created_at).toLocaleDateString()}</td>
                    <td>
                        <button class="action-btn btn-edit" onclick="editUser(${user.id})">编辑</button>
                        <button class="action-btn btn-delete" onclick="deleteUser(${user.id}, '${idNumber}')">删除</button>
                    </td>
                </tr>
            `;
        }).join('');
    }
    
    function getRoleName(role) {
        const names = {
            'admin': '管理员',
            'teacher': '教师',
            'student': '学生'
        };
        return names[role] || role;
    }
    
    function showCreateModal() {
        document.getElementById('modal-title').textContent = '创建用户';
        document.getElementById('user-form').reset();
        document.getElementById('user-id').value = '';
        document.getElementById('password-hint').textContent = '*';
        document.getElementById('password').required = true;
        document.getElementById('user-modal').style.display = 'block';
        handleRoleChange();
    }
    
    function editUser(userId) {
        const user = allUsers.find(u => u.id === userId);
        if (!user) return;
        
        document.getElementById('modal-title').textContent = '编辑用户';
        document.getElementById('user-id').value = user.id;
        document.getElementById('username').value = user.username;
        document.getElementById('email').value = user.email || '';
        document.getElementById('password').value = '';
        document.getElementById('password-hint').textContent = '(留空则不修改)';
        document.getElementById('password').required = false;
        document.getElementById('role').value = user.role;
        document.getElementById('first-name').value = user.first_name || '';
        document.getElementById('last-name').value = user.last_name || '';
        document.getElementById('college').value = user.college || '';
        document.getElementById('department').value = user.department || '';
        document.getElementById('phone').value = user.phone || '';
        
        handleRoleChange();
        
        // 填充profile数据
        if (user.profile) {
            if (user.role === 'student') {
                document.getElementById('student-id').value = user.profile.student_id || '';
                document.getElementById('major').value = user.profile.major || '';
                document.getElementById('grade-level').value = user.profile.grade_level || '1';
                if (user.profile.enrollment_date) {
                    const d = new Date(user.profile.enrollment_date);
                    const iso = d.toISOString().slice(0,10);
                    document.getElementById('enrollment-date').value = iso;
                } else {
                    document.getElementById('enrollment-date').value = '';
                }
            } else if (user.role === 'teacher') {
                document.getElementById('employee-id').value = user.profile.employee_id || '';
                document.getElementById('teacher-department').value = user.profile.department || '';
                document.getElementById('title').value = user.profile.title || '';
            }
        }
        
        document.getElementById('user-modal').style.display = 'block';
    }
    
    function handleRoleChange() {
        const role = document.getElementById('role').value;
        document.getElementById('student-fields').style.display = role === 'student' ? 'block' : 'none';
        document.getElementById('teacher-fields').style.display = role === 'teacher' ? 'block' : 'none';
    }
    
    async function saveUser() {
        try {
            const userId = document.getElementById('user-id').value;
            const isEdit = !!userId;
            
            const userData = {
                username: document.getElementById('username').value,
                email: document.getElementById('email').value || null,
                role: document.getElementById('role').value,
                first_name: document.getElementById('first-name').value,
                last_name: document.getElementById('last-name').value,
                college: document.getElementById('college').value,
                department: document.getElementById('department').value,
                phone: document.getElementById('phone').value
            };
            
            const password = document.getElementById('password').value;
            if (password) {
                userData.password = password;
            }
            
            // 添加role特定字段
            if (userData.role === 'student') {
                userData.student_id = document.getElementById('student-id').value;
                userData.major = document.getElementById('major').value;
                userData.grade_level = parseInt(document.getElementById('grade-level').value);
                const ed = document.getElementById('enrollment-date').value;
                if (ed) userData.enrollment_date = ed;
            } else if (userData.role === 'teacher') {
                userData.employee_id = document.getElementById('employee-id').value;
                userData.department = document.getElementById('teacher-department').value;
                userData.title = document.getElementById('title').value;
            }
            
            const url = isEdit ? `/users/${userId}` : '/users';
            const method = isEdit ? 'PUT' : 'POST';
            
            const data = await apiRequest(url, {
                method: method,
                body: JSON.stringify(userData)
            });
            
            if (data.success) {
                showAlert(isEdit ? '用户更新成功' : '用户创建成功', 'success');
                closeModal();
                loadUsers();
            }
        } catch (error) {
            showAlert('操作失败: ' + error.message, 'error');
        }
    }
    
    async function deleteUser(userId, username) {
        if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可恢复！`)) {
            return;
        }
        
        try {
            const data = await apiRequest(`/users/${userId}`, {
                method: 'DELETE'
            });
            
            if (data.success) {
                showAlert('用户删除成功', 'success');
                loadUsers();
            }
        } catch (error) {
            showAlert('删除失败: ' + error.message, 'error');
        }
    }
    
    function closeModal() {
        document.getElementById('user-modal').style.display = 'none';
    }
    
    // 搜索功能
    document.getElementById('search-input')?.addEventListener('input', (e) => {
        const keyword = e.target.value.toLowerCase();
        const filtered = allUsers.filter(user => {
            // 组合完整姓名进行匹配
            const fullName = (user.last_name || '') + (user.first_name || '');
            
            return user.username.toLowerCase().includes(keyword) ||
                (user.email && user.email.toLowerCase().includes(keyword)) ||
                (user.first_name && user.first_name.toLowerCase().includes(keyword)) ||
                (user.last_name && user.last_name.toLowerCase().includes(keyword)) ||
                fullName.toLowerCase().includes(keyword) ||
                (user.college && user.college.toLowerCase().includes(keyword)) ||
                (user.department && user.department.toLowerCase().includes(keyword));
        });
        renderUsers(filtered);
    });
    
    // 页面加载
    window.addEventListener('DOMContentLoaded', () => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
        if (userInfo.role !== 'admin') {
            showAlert('权限不足', 'error');
            setTimeout(() => window.location.href = '/', 2000);
            return;
        }
        
        loadUsers();
    });
    
    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('user-modal');
        if (event.target === modal) {
            closeModal();
        }
    }
</script>
{% endblock %}





